package cn.itcast.anli.web;

import cn.itcast.anli.domain.Account;
import cn.itcast.anli.service.AccountService;
import cn.itcast.anli.service.impl.AccountServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/servletLogin")
public class LoginServlet extends HttpServlet {
    AccountService accountService = new AccountServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("UTF-8");
        //从前端获取用户名、密码、验证码这三个数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkcode = request.getParameter("checkcode");
        //从session中获取验证码属性的值
        HttpSession session = request.getSession();
        String checkcode_session = (String)session.getAttribute("checkcode");
        //删除session中存储的验证码，使验证码一次有效
        session.removeAttribute("checkcode");
        //将验证码与用户输入的验证码进行比对,忽略大小写
        //当登陆后页面回退，删除session中存储的验证码后，其可能为null，所以要先进行判断
        if (checkcode_session == null){
            request.setAttribute("code_msg","验证码输入有误！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
        //验证码输入错误，向request域中存入code_msg键值对，请求转发回登陆页面，显示验证码输入错误
        else if (!checkcode_session.equalsIgnoreCase(checkcode)){
            request.setAttribute("code_msg","验证码输入有误！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else{
            //如果验证码无误，将用户信息封装成对象
            Account account = new Account(username, password);
            //将账户对象传入service层，接收service层返回的参数
            Boolean login = accountService.login(account);
            //如果在数据库中找到了匹配的数据
            if (login){
                //重定向到跳转页面
                response.sendRedirect(request.getContextPath()+"/index.jsp");
                //向session中传入键值对，键名username，以供跳转页面显示用户名称
                session.setAttribute("username",username);
            }else {
                //用户名或密码输入错误，向request域中存入login_msg键值对，请求转发回登陆页面，用户名或密码输入错误
                request.setAttribute("login_msg","用户名或密码输入有误！");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }

        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
